<template>
  <q-page class="q-pa-md">
    <div class="column q-gutter-md">
      <q-card v-for="(category, index) in categories" :key="category">
        <q-card-section>
          <div :id="`chart-container-${index}`" style="height: 500px;"></div>
        </q-card-section>
      </q-card>
    </div>
  </q-page>
</template>

<script>
import * as echarts from 'echarts/core'
import { BarChart, PieChart } from 'echarts/charts'
import { TitleComponent, GridComponent, TooltipComponent, LegendComponent } from 'echarts/components'
import { CanvasRenderer } from 'echarts/renderers'

echarts.use([BarChart, PieChart, TitleComponent, GridComponent, TooltipComponent, CanvasRenderer, LegendComponent])

export default {
  data() {
    return {
      categories: ['告警名称', '网元类型', '告警类型'],
      mockGroupData: {
        '告警名称': { chartData: [] },
        '网元类型': { chartData: [] },
        '告警类型': { chartData: [] }
      },
      chartInstances: [],
      colorPalette: [
        '#5470c6', '#91cc75', '#fac858',
        '#ee6666', '#73c0de', '#3ba272',
        '#fc8452', '#9a60b4', '#ea7ccc'
      ]
    }
  },
  mounted() {
    this.requestData(this.nameQuery, '告警名称')
    this.requestData(this.levelQuery, '网元类型')
    this.requestData(this.businessQuery, '告警类型')
    this.$nextTick(() => {
      this.initCharts()
    })
  },
  methods: {
    requestData(query, category) {
      fetch('http://1.95.80.5:9002/tonghua_gaojing/_search', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Basic ' + btoa('admin:1992A1573')
        },
        body: JSON.stringify(query)
      })
      .then(response => response.json())
      .then(data => {
        this.mockGroupData[category]['chartData'] = data.aggregations.group_by_field.buckets
        // console.log(this.mockGroupData[category].chartData)
      })
      .catch(error => console.error('Error fetching data:', error))
    },
    initCharts() {
      this.categories.forEach((category, index) => {
        if (!this.chartInstances[index]) {
          const dom = document.getElementById(`chart-container-${index}`)
          if (dom) {
            this.chartInstances[index] = echarts.init(dom)
          }
        }
        const chart = this.chartInstances[index]
        const data = this.mockGroupData[category]

        chart.setOption({
          title: {
            text: category + '统计',
            show: true,
            left: 'center',
            textStyle: { fontSize: 18 }
          },
          tooltip: {
            trigger: category === '告警类型' ? 'axis' : 'item',
            formatter: category === '告警类型' ? '{b}: {c}' : '{b}: {c} ({d}%)',
            axisPointer: { type: 'shadow' }
          },
          ...(category === '告警类型' ? {
            xAxis: {
              type: 'category',
              data: data.chartData.map(item => item.key),
              axisLabel: {
                rotate: 30,
                interval: 0,
                formatter: value => value.length > 6 ? value.substr(0, 6) + '...' : value
              }
            },
            yAxis: {
              type: 'value',
              axisLabel: { formatter: '{value}' }
            }
          } : {}),
          series: [{
            name: '总数',
            type: category === '告警类型' ? 'bar' : 'pie',
            color: this.colorPalette,
            ...(category === '告警类型' ? {
              label: { show: true, position: 'top', formatter: '{c}' },
              itemStyle: { color: params => this.colorPalette[params.dataIndex % 9] }
            } : {
              radius: ['15%', '65%'],
              roseType: 'area',
              center: ['50%', '50%'],
              minAngle: 15,
              startAngle: 90,
              stillShowZeroSum: true,
              avoidLabelOverlap: false,
              labelLine: { show: true, length: 10, length2: 15 },
              label: {
                show: true,
                position: 'outside',
                formatter: '{b|{b}}\n{c} ({d}%)',
                backgroundColor: '#fff',
                borderColor: '#ccc',
                borderWidth: 1,
                padding: [5, 10],
                rich: { b: { fontSize: 12, lineHeight: 20 } }
              },
              itemStyle: {
                opacity: 0.8,
                borderRadius: 3,
                borderWidth: 1,
                borderColor: '#fff',
                shadowBlur: 5,
                shadowColor: 'rgba(0, 0, 0, 0.3)'
              },
              emphasis: {
                label: { show: true, fontSize: 14 },
                itemStyle: {
                  opacity: 1,
                  shadowBlur: 10,
                  shadowColor: 'rgba(0, 0, 0, 0.5)'
                }
              }
            }),
            data: data.chartData.map(item => ({
              name: item.key,
              value: item.doc_count
            }))
          }]
        })
      })
    }
  },
  computed: {
    nameQuery() {
      return {
        "size": 0,
        "aggs": { "group_by_field": { "terms": { "field": "名称.keyword" } } }
      }
    },
    levelQuery() {
      return {
        "size": 0,
        "aggs": { "group_by_field": { "terms": { "field": "网元类型.keyword" } } }
      }
    },
    businessQuery() {
      return {
        "size": 0,
        "aggs": { "group_by_field": { "terms": { "field": "告警类型.keyword" } } }
      }
    }
  },
  watch: {
    mockGroupData: {
      deep: true,
      handler() {
        this.$nextTick(() => {
          this.initCharts()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.q-card {
  transition: transform 0.3s;
  &:hover {
    transform: translateY(-5px);
  }
}
</style>